package com.chuangke.file.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;

import com.chuangke.admin.service.SysUserDataDeptService;
import com.chuangke.admin.service.SysUserRoleService;
import com.chuangke.common.event.file.FileDbankRegistEvent;
import com.chuangke.common.event.file.FilePermissionChangeEvent;
import com.chuangke.common.event.file.FileUpdateEvent;
import com.chuangke.common.event.file.FileUploadEvent;
import com.chuangke.file.model.FileInfo;
import com.chuangke.file.service.FileDbankService;
import com.chuangke.file.service.FileHandleService;
import com.chuangke.file.service.SysFilePermissionService;
import com.chuangke.fss.FSSConfig;

@Configuration
public class FileHandleListener {
	
	private static final Logger logger = LoggerFactory.getLogger(FileHandleListener.class);

	@Autowired
	private FileHandleService fileHandleService;
	@Autowired
	private FileDbankService fileDbankService ;
	@Autowired
	private SysFilePermissionService SysFilePermissionService ;
	@Autowired
	private SysUserDataDeptService sysUserDataDeptService ;
	@Autowired
	private SysUserRoleService sysUserRoleService ;
	@Autowired
	private FSSConfig fssConfig;

	@EventListener
	public void handleFileUpdateEvent(FileUpdateEvent event) {
		if(!fssConfig.isOpenElasticsearch) {
			return ;
		}
		logger.info("文件修改，同步elasticsearch");
		fileHandleService.updateElasticByFileId(event.getFileIds());
	}

	@EventListener
	public void handleFileUploadEvent(FileUploadEvent event) {
//		if(!fssConfig.isOpenElasticsearch) {
//			return ;
//		}
		logger.info("文件上传，同步elasticsearch");
		fileHandleService.handle((FileInfo)event.getFileInfo());
	}
	
	@EventListener
	public void handleFileDbankRegistEvent(FileDbankRegistEvent event) {
		if(!fssConfig.isAutoRegisterDbank) {
			return ;
		}
		logger.info("网盘注册：{}",event.getRemarks());
		fileDbankService.regist(event.getBelongId(), event.getDbankType(), event.getRemarks(), event.getLimitSpace());
	}
	
	@Async
	@EventListener
	public void handleFilePermissionChangeEvent(FilePermissionChangeEvent event) {
		if(!fssConfig.isAutoRegisterDbank) {
			return ;
		}
		logger.info("网盘权限变更-开始");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		SysFilePermissionService.change();
		sysUserDataDeptService.findAll() ;
    	sysUserRoleService.findAll() ;
    	logger.info("网盘权限变更-结束");
	}

}
